//
//  WebViewController.m
//  sensen_ios
//
//  Created by mc on 16/3/28.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "WebViewController.h"
#import "NSString+Helper.h"



@interface WebViewController ()<UMSocialUIDelegate>
{
    UILabel *_loadLabel; // 网页加载提示文字
    UIActivityIndicatorView *_indicatorView; // 网页加载菊花转动
    NSString *_string;
}




@end

@implementation WebViewController

// 自定义初始化方法，获取所要显示的网页的网址，并显示该网页
- (instancetype)initWithUrlString:(NSString *)urlString {
    self = [super init];
    if (self) {
        // 创建网页webView
        CGRect frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT -15);
        _webView = [[UIWebView alloc] initWithFrame:frame];
        _webView.delegate = self;
        _webView.scalesPageToFit = YES;
        [self.view addSubview:_webView];
        _string = urlString;
        // 发送请求，获取该网页内容
        urlString = [urlString stringByEncodingURLFormat];
        
        NSURL *url = [NSURL URLWithString:urlString];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
        [_webView loadRequest:request];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
}



- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    
    //导航栏默认黄色
    if (!self.color) {
        self.color = SS_NAVI_ORANGE_COLOR;
    }
    // 设置背景颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:self.color] forBarMetrics:UIBarMetricsDefault];
    
    self.title =  self.titleString;
    // 进来的时候要隐藏导航栏
    MainTabBarController *tabBarController = (MainTabBarController *)self.navigationController.tabBarController;
    [tabBarController hideTabBar];
    
    //  创建导航栏左边返回按钮，此方法由父类实现
    [self createLeftBarButtonItemWithImagename:nil];
}
// 右侧按钮的样式可以自定义，由imgname控制，如果是文字则调用下面的接口
- (void)createRightBarButtonItemWithImagename:(NSString *)imgname {
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    [rightButton addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setImage:[UIImage imageNamed:imgname] forState:UIControlStateNormal];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButton;
}

#pragma mark - UIVebView代理方法
// 开始加载
- (void)webViewDidStartLoad:(UIWebView *)webView {
    // 创建提示文字
    _loadLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
    _loadLabel.text = @"加载中...";
    _loadLabel.textAlignment = NSTextAlignmentCenter;
    _loadLabel.textColor = [UIColor lightGrayColor];
    _loadLabel.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:_loadLabel];
    
    // 加载网页时，菊花转动
    _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    CGPoint point = CGPointMake(self.view.width/4, -20);
    _indicatorView.center = point;
    [_loadLabel addSubview:_indicatorView];
    _indicatorView.hidesWhenStopped = YES;
    [_indicatorView startAnimating];
}

// 加载结束
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    // 加载提示移除
    [_indicatorView stopAnimating];
    [_loadLabel removeFromSuperview];
    _loadLabel = nil;
}


#pragma mark - 返回上一界面
// 返回上一界面，覆写父类方法
- (void)leftAction:(UIButton *)button {
    if (_webView.canGoBack) {
        [_webView goBack];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}



- (void)rightAction:(UIButton *)button{
    
        NSString *shareText = @"森森分享有礼"; 
        NSString *url = _string; // 要分享的网址
        // 微信处理
        [UMSocialWechatHandler setWXAppId:APPKEY_WEIXIN appSecret:APPSECRET_WEIXIN url:url];
        [UMSocialQQHandler setQQWithAppId:APPID_QQ appKey:APPKEY_QQ url:url];
        
        
        // TODO: 分享链接的问题®
        // 微博分享的处理
        [UMSocialData defaultData].extConfig.sinaData.shareText = shareText;
        [UMSocialData defaultData].extConfig.sinaData.urlResource.url = url;
        [UMSocialData defaultData].extConfig.sinaData.urlResource.resourceType = UMSocialUrlResourceTypeImage;
        
        // 微信消息类型
        [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
        
        // 微信朋友圈分享
        [UMSocialData defaultData].extConfig.wechatTimelineData.title = @"微信朋友圈分享title";
        [UMSocialData defaultData].extConfig.wechatTimelineData.url = url;
        
        // 微信好友分享
        [UMSocialData defaultData].extConfig.wechatSessionData.title = @"微信好友分享title";
        [UMSocialData defaultData].extConfig.wechatSessionData.url = url;
        
        // qq分享
        [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
        [UMSocialData defaultData].extConfig.qqData.title = @"QQ分享title";
        [UMSocialData defaultData].extConfig.qzoneData.title = @"QQ空间分享title";
        [UMSocialData defaultData].extConfig.qqData.url = url;
        [UMSocialData defaultData].extConfig.qzoneData.url = url;
        
        // 实现分享
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:APPKEY_UMENG_SOCIAL
                                          shareText:shareText
                                         shareImage:DEFAULT_IMAGE
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToQQ,UMShareToWechatSession,UMShareToWechatTimeline,nil]
                                           delegate:self];
        
        
        // 使用自定义分享列表面板，则在对应的（微信，qq，微博等）分享按钮中实现下面的方法
        //    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession]
        //                                                       content:@"分享内嵌文字"
        //                                                         image:nil
        //                                                      location:nil
        //                                                   urlResource:nil
        //                                           presentedController:self
        //                                                    completion:^(UMSocialResponseEntity *response) {
        //        if (response.responseCode == UMSResponseCodeSuccess) {
        //            NSLog(@"分享成功！");
        //        }
        //    }];
    

}



- (BOOL)webView: (UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *requestString = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSLog(@"请求网址  ＝ %@", requestString);
    
    if ([requestString hasPrefix:@"com.itboye.sunsunchina:"]) {
        
        NSArray *kv = [requestString componentsSeparatedByString:@"="];
        NSString * getString;
        if (kv.count == 2) {
            getString =[[kv objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
        
        if ([getString isEqualToString:@"SUNSUN_COM"]) {//森森官网
            WebViewController  *vc = [[WebViewController alloc] initWithUrlString:@"http://m.sunsuncn.com/"];
            vc.titleString = @"森森官网";
            [self.navigationController pushViewController:vc animated:YES];
        }
        return NO;
    }
    return YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
